<!--
  移动签批->公文详情->发文->修改公文要素
-->
<template>
  <view>
    <van-popup v-model="showCompo" closeable round position="bottom" :style="{ height: '100%' }"
               @click-close-icon="toClose" @click-overlay="toClose">
      <van-row type="flex" justify="center">
        <van-col offset="1" span="8">
          <van-cell value="修改公文要素"/>
        </van-col>
      </van-row>
      <van-form>
        <van-collapse v-model="tableShow" accordion :border="border">
          <van-collapse-item icon="label-o" title="公文要素" title-class="text-bold" name="jbxx">
            <van-field ref="title" v-model="formData.title" required label="公文标题" placeholder="请输入" input-align="right"
                       autosize rows="1" type="textarea"/>

            <van-cell ref="jjcd" required is-link title="紧急程度"
                      :value="this.dict.getDictNameByDictCode('jjcd',formData.emergencyLevel)" @click="show1 = true"/>
            <van-action-sheet v-model="show1" :actions="hj" cancel-text="取消" @select="onSelect1"/>


            <van-cell ref="name" required title="拟稿人" :value="formData.drafterName" @click="showDrafterSheet" is-link/>
            <drafter :showDrafter="showDrafter" :nodeData="nodeDataDrafter" :drafterData="drafterData"
                     @closeDrafterSheet="closeDrafterSheet"></drafter>

            <van-field v-model="formData.drafterPhone" label="电话" type="tel" placeholder="请输入" input-align="right"/>
            <van-field v-model="formData.remark" label="备注" placeholder="请输入" input-align="right"/>
          </van-collapse-item>
          <van-collapse-item icon="font-o" title="已附加公文" title-class="text-bold" name="zwjfj">
            <view class="opinion" v-if="relation.length>0 ">
              <text class="opinion-left">附加公文</text>
              <view class="opinion-right">
                <text v-for="(item,index) in relation">{{ item.title }}</text>
              </view>
            </view>
          </van-collapse-item>
        </van-collapse>
      </van-form>

      <view class="padding-top-lg padding-bottom-lg">
        <van-row type="flex" justify="space-around">
          <van-col span="10">
            <van-button type="info" round plain hairline block @click="toClose">取消</van-button>
          </van-col>
          <van-col span="10">
            <van-button type="info" round block @click="toEdit">确定</van-button>
          </van-col>
        </van-row>
      </view>
    </van-popup>
  </view>
</template>

<script>
import forward from 'pages/caac/components/submitDoc/compo-forward';
import orgTree from 'pages/caac/components/submitDoc/compo-orgtree';//单位选择组件
import signOrg from 'pages/caac/components/submitDoc/compo-signorg';//会签单位选择组件
import drafter from 'pages/caac/components/common/compo-drafter';//拟稿人选择
export default {
  components: {
    forward,
    orgTree,
    signOrg,
    drafter
  },
  props: {
    showEdit: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    showEdit(val) {
      this.showCompo = val
    },
  },
  data() {
    return {
      showCompo: false,//组件是否显示
      showCalendar: false,//日历组件显示
      //1主送 3抄送 4分送
      forwardState1: false,//分送
      forwardState3: false,//抄送
      forwardState4: false,//分送
      showOrgtree: false,//显示机构树
      showSignOrg: false,//会签单位选择
      showDrafter: false,//拟稿人组件
      //拟稿人选择，查询单位所需节点和隐藏节点
      nodeDataDrafter: {
        showNode: '', //显示的节点
        hideNode: '', //隐藏的节点
      },
      //拟稿人信息，串回子组件回显用
      drafterData: {
        userName: '',
        userId: ''
      },
      countersign: [],//会签单位名称数组
      countersignValue: [],//会签单位值数组
      relation: [],//附加公文列表
      ready: false, // 这里用于自主控制loading加载状态，避免异步正在加载数据的空档显示“暂无数据”
      showOrg: false,
      formData: {},//表单数据
      showPopup: false,
      border: false,
      show: false,
      show1: false,
      show2: false,
      show3: false,
      show4: false,
      show5: false,
      show6: false,
      show7: false,
      show8: false,
      tableShow: "jbxx",
      zwjfj: '',
      mj: [],
      hj: [],
      xzxklgw: [],
      sfgk: [],
      wjsx: [],
      sfwzyzcwj: [],
      sfyjjfa: [],
      sfwywjhfxshhjg: [],
      bgqx: [],//保管期限
      sfdcfkgw: [],
      sfsdcsx: [],
      title: '',
      countersignDept: '',
      countersignDeptId: '',
      dictSecrecyLevel: [],
      dictEmergencyLevel: [],
      dictXzsplgw: [],
      dictInfoDisclosure: [],
      dictFileAttribute: [],
      dictIsPolicy: [],
      dictIsInterpret: [],
      dictIsLegal: [],
      dictBgqx: [],
      dictIsSupervise: [],
    };
  },
  mounted() {
    this.getDict()//获取字典项
    this.getShowDept()//获取要显示的组织机构
  },
  methods: {

    //拟稿人
    showDrafterSheet() {
      this.showDrafter = true
    },
    //关闭拟稿人组件
    closeDrafterSheet(userInfo) {
      //userInfo: {"userId":"4926","userName":"高萌"}
      this.formData.drafterId = userInfo.userId
      this.formData.drafterName = userInfo.userName
      this.showDrafter = false
    },
    onConfirm(date) {
      const formatDate = (date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
      this.showCalendar = false
      this.formData.endlineTime = formatDate(date)
    },
    //类型 1主送 3抄送 4分送
    showforward(tagType) {
      if (tagType == 1) {
        this.forwardState1 = true
      } else if (tagType == 3) {
        this.forwardState3 = true
      } else if (tagType == 4) {
        this.forwardState4 = true
      }

    },

    //子组件通知父组件关闭
    closeSheet(data) {
      //1主送 3抄送 4分送
      console.log("tagType: " + JSON.stringify(data));
      if (data.tagType == 1) {
        if (data.tagId != '') {
          this.formData.mainTo = data.content
        }
        this.forwardState1 = false
      } else if (data.tagType == 3) {
        if (data.tagId != '') {
          this.formData.copyTo = data.content
        }
        this.forwardState3 = false
      } else if (data.tagType == 4) {
        if (data.tagId != '') {
          this.formData.copyReports = data.content
        }
        this.forwardState4 = false
      }

    },

    //点击会签单位
    showSignOrgSheet() {
      this.showSignOrg = true
    },
    //子组件通知父组件关闭机构树
    closeSignOrgSheet(data) {
      // data:["办公室","航安办"]
      console.log("org ---- data: " + JSON.stringify(data));
      this.countersign = []//置空，以防多次追加
      this.formData.countersign = data.toString()//给表单赋值，提交表单用
      this.showSignOrg = false
    },
    //密级
    onSelect(item) {
      //item: {"name":"无","dictItemCode":"1"}
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      this.formData.secrecyLevel = item.dictItemCode
      // this.formData.secrecyLevelName = item.name
      this.show = false;
    },
    //缓急
    onSelect1(item) {
      this.formData.emergencyLevel = item.dictItemCode
      // this.formData.emergencyLevelName = item.name
      this.show1 = false;
    },
    //行政许可类公文
    onSelect2(item) {
      this.formData.xzsplgw = item.dictItemCode
      // this.formData.xzsplgwName = item.name
      this.show2 = false;
    },
    //是否公开
    onSelect3(item) {
      this.formData.infoDisclosure = item.dictItemCode
      // this.formData.infoDisclosureName = item.name
      this.show3 = false;
    },
    //文件属性
    onSelect4(item) {
      this.formData.fileAttribute = item.dictItemCode
      // this.formData.fileAttributeName = item.name
      this.show4 = false;
    },
    //是否为重要政策性文件
    onSelect5(item) {
      //如果选择是，则是否有解读文件和是否有文件合法性审核结果都为选中
      if (item.name == '是') {
        //[{"name":"是","dictItemCode":"1"},{"name":"否","dictItemCode":"2"}]
        this.formData.isInterpret = this.sfyjjfa.filter(v => v.name == '是')[0].dictItemCode
        this.formData.isLegal = this.sfwywjhfxshhjg.filter(v => v.name == '是')[0].dictItemCode
      }
      this.formData.isPolicy = item.dictItemCode
      // this.formData.isPolicyName = item.name
      this.show5 = false;
    },
    //是否有解读方案
    onSelect6(item) {
      this.formData.isInterpret = item.dictItemCode
      // this.formData.isInterpretName = item.name
      this.show6 = false;
    },
    //是否有文件合法性审查结果
    onSelect7(item) {
      this.formData.isLegal = item.dictItemCode
      // this.formData.isLegalName = item.name
      this.show7 = false;
    },
    onSelect8(item) {
      this.formData.storagePeriod = item.dictItemCode
      // this.formData.isSuperviseName = item.name
      this.show8 = false;
    },
    //取消按钮
    toClose() {
      this.$emit('closeEdit', this.showEdit);
    },
    //确定按钮
    toEdit() {
      this.saveelement()
    },
    // 表单校验
    validateForm() {
      if (this.util.isEmpty(this.formData.title)) {
        this.$refs.title.focus()
        this.$toast('请填写标题')
        return false
      }

      if (this.util.isEmpty(this.formData.drafterName)) {
        this.$refs.name.focus()
        this.$toast('请填写拟稿人')
        return false
      }
      if (this.util.isEmpty(this.formData.emergencyLevel)) {
        this.$refs.jjcd.focus()
        this.$toast('请选择紧急程度')
        return false
      }
      return true;
    },
    //修改公文要素
    saveelement() {
      console.log("修改公文要素==>: " + JSON.stringify(this.formData));
      var _this = this
      if (_this.validateForm()) {
        this.$httploading({
          //修改呈批件接口和发文发电不一样
          url: this.$http.adornUrl(`/caac/oa/mhjapprovaldoc?systemKey=` + this.cache.get('userInfo').systemKey + `&systemFlag=` + this.cache.get('userInfo').systemFlag),
          method: 'post',
          data: JSON.stringify(this.formData)

        }).then(({data}) => {
          console.log("修改公文要素data: " + JSON.stringify(data));
          if (data.code == 200) {
            _this.$toast('修改公文要素成功')
            _this.$emit('closeEdit', this.showEdit);
            _this.$emit('refreshBtnGroup', true)//修改成功后通知父组件重新加载数据
            // console.log("_this.formData: " + JSON.stringify(_this.formData));
          }
        })
      }
    },
    //父组件点击修改公文要素时调用获取详情回显到表单
    editGw(proInstId) {

      console.log("获取公文要素详情" + proInstId);
      var _this = this
      this.$httploading({
        url: this.$http.adornUrl(`/caac/oa/doc/fw/proInstId/` + proInstId),
        method: 'get',
        params: this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,//固定值
          'systemFlag': this.cache.get('userInfo').systemFlag//固定值
          // 'systemKey': 'ls_liu',//固定值
          // 'systemFlag': 'yidong'//固定值
        })
      }).then(({data}) => {
        console.log("获取公文要素详情data: " + JSON.stringify(data));
        if (data.code == 200) {
          _this.formData = data.data
          this.drafterData.userId = _this.formData.drafterId
          this.drafterData.userName = _this.formData.drafterName
          _this.getRelation(data.data.extendIdForRelate)
        }
      })
    },
    //获取附加公文
    getRelation(extendIdForRelate) {
      // proInstId = 'f9525d014c5348fb866daca4879ae905'//TODO 暂时写死
      var _this = this
      this.$http({
        url: this.$http.adornUrl(`/caac/oa/mhjComponent/relationfile/relation`),
        method: 'get',
        params: this.$http.adornParams({
          'docId': extendIdForRelate,
          'systemKey': this.cache.get('userInfo').systemKey,//固定值
          'systemFlag': this.cache.get('userInfo').systemFlag//固定值
        })
      }).then(({data}) => {
        //[{"id":"1c0962f8839d46f792f84e5c89c96f14","title":"ppap","relateDocId":"4ec205b8334446f9b932d0fcb3896bc8","proInstId":"4ec205b8334446f9b932d0fcb3896bc8"},{"id":"2f4aa437ecba4c748bff911f03667147","title":"py","relateDocId":"86d30c881c494b468534685bb0746174","proInstId":"86d30c881c494b468534685bb0746174"}]
        if (data.code == 200) {
          if (data.data != null) {
            _this.relation = data.data
          }
        }
        console.log("附加公文: " + JSON.stringify(data));
      })
    },
    // 只有在"点击"修改的指定节点会触发(也就是说这个方法只会触发一次)，obj中包含当前选中
    handleCheck(obj) {
      // obj: {
      // 	checkedKeys: [9, 5], // 当前选中节点的id数组
      // 	checkedNodes: [{...}, {...}], // 当前选中节点数组
      // 	data: {...}, // 当前节点的数据
      // 	halfCheckedKeys: [1, 4, 2], // 半选中节点的id数组
      // 	halfCheckedNodes: [{...}, {...}, {...}], // 半选中节点的数组
      // 	node: Node {...} // 当前节点实例
      // }

      // console.log('handleCheck', obj);
    },

    // 只要节点的选中状态改变就触发（包括设置默认选中，点击选中/取消选中），会被触发多次
    handleRadioChange(obj) {
      // console.log("obj: " + JSON.stringify(obj));
      if (obj.checked == true) {//{"checked":false,"node":{"time":1629361630143,"id":3459,"text":null,"checked":false,"indeterminate":false,"data":{"deptId":"002001","deptCode":"002001","deptName":"华北管理局","leaderId":"sysadmin","parentId":"002","allParentId":"0,002,002001","deptLevel":1,"sort":36,"deptType":"org","divisionId":"--","telephone":"11","address":"1","zipCode":"1     ","extend1":"华北管理局","extend2":null,"extend3":null,"extend4":null,"extend5":null,"extend6":"002001","extend7":null,"extend8":null,"extend9":null,"extend10":null,"isValid":"1","createUser":"CAAC_SYSTEM","createTime":"2021-07-27T12:30:00.011+0000","updateUser":null,"updateTime":null,"depth":null}}
        console.log(obj.node.data.deptName)//单位名称
        console.log(obj.node.data.deptId)//单位id
        this.countersignDept = obj.node.data.deptName
        this.countersignDeptId = obj.node.data.deptId
      } else {
        this.countersignDept = ''
        this.countersignDeptId = ''
      }
      // console.log('handleRadioChange', obj);
    },

    handleNodeClick(obj) {
      // console.log('handleNodeClick', JSON.stringify(obj));
      // console.log('getNodePath', this.$refs.tree.getNodePath(obj.data));
    },
    //呈报单位查询
    filterNode(value, data) {
      if (!value) return true;
      return data.deptName.indexOf(value) !== -1;
    },
    //获取要显示的组织机构代码
    getShowDept() {
      this.$http({
        url: this.$http.adornUrl(`/caac/oa/doc/fw/getShowDept`),
        method: 'get',
        params: this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,//固定值
          'systemFlag': this.cache.get('userInfo').systemFlag//固定值
        })
      }).then(({data}) => {
        if (data.code == 200) {
          if (data.data != null) {
            this.nodeDataDrafter.showNode = data.data.hideDepts
            this.nodeDataDrafter.hideNode = ''//要隐藏的节点
          }
        }
      })
    },
    //获取需要的字典项
    getDict() {
      

      this.dictEmergencyLevel = this.cache.get('jjcd')//紧急程度
      this.hj = []
      this.dictEmergencyLevel.forEach((item) => {
        this.hj.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })

      this.dictXzsplgw = this.cache.get('xzsplgw')//紧急程度
      this.xzxklgw = []
      this.dictXzsplgw.forEach((item) => {
        this.xzxklgw.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })


      this.dictInfoDisclosure = this.cache.get('infopublic')
      this.sfgk = []
      this.dictInfoDisclosure.forEach((item) => {
        this.sfgk.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })

      this.dictFileAttribute = this.cache.get('fileAttribute')//文件属性
      this.wjsx = []
      this.dictFileAttribute.forEach((item) => {
        this.wjsx.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })

      this.dictIsPolicy = this.cache.get('isPolicy')//是否为重要政策性文件
      this.sfwzyzcwj = []
      this.dictIsPolicy.forEach((item) => {
        this.sfwzyzcwj.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })

      this.dictIsInterpret = this.cache.get('isInterpret')//是否有解决方案
      this.sfyjjfa = []
      this.dictIsInterpret.forEach((item) => {
        this.sfyjjfa.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })

      this.dictIsLegal = this.cache.get('isLegal')//是否有文件合法性审查结果
      this.sfwywjhfxshhjg = []
      this.dictIsLegal.forEach((item) => {
        this.sfwywjhfxshhjg.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })

      //保管期限
      this.dictBgqx = this.cache.get('bgqx')//是否有文件合法性审查结果
      this.bgqx = []
      this.dictBgqx.forEach((item) => {
        this.bgqx.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })

      this.dictIsSupervise = this.cache.get('isSupervise')//是否有文件合法性审查结果
      this.sfdcfkgw = []
      this.dictIsSupervise.forEach((item) => {
        this.sfdcfkgw.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })
      console.log("======================: " + JSON.stringify(this.dictIsPolicy));
    },


  },


};
</script>

<style scoped>
  /* 意见相关样式 */
  .opinion{
    display: flex;
    flex-direction: column;
    margin: 0 32rpx;
    padding: 20rpx 0rpx;
    overflow: hidden;
    font-size: 28rpx;
    line-height: 24px;
    border-bottom: 1px solid #ebedf0;

  }
  .opinion .opinion-left{
    text-align: left;
    color: #323233;
  }
  .opinion .opinion-right{
    text-align: right;
    color: #969799;
  }
	.van-cell__title {
		min-width: 55%;

		span {
			display: inline-block;
			text-align: left;
			word-break: break-all;
		}
	}

	/deep/ .van-collapse-item__content {
		padding: 0px;
		color: #969799;
		font-size: 14px;
		line-height: 1.5;
		background-color: #fff;
	}

	/deep/ .van-field__label {
		color: #323233;
		min-width: 50%;

		span {
			display: inline-block;
			text-align: left;
			word-break: break-all;
		}
	}

	/deep/ .van-field__control {
		font-size: 14px;
		color: #969799;
	}
</style>
